package com.imageim.yimirror.ui.fragment.tendency;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.imageim.yimirror.R;
import com.imageim.yimirror.bean.FashionBrandBean;
import com.imageim.yimirror.bean.FashionRecommendBean;
import com.imageim.yimirror.bean.LikeEventInfo;
import com.imageim.yimirror.bean.tendency.TendencyThemeItemBean;
import com.imageim.yimirror.common.event.EventCode;
import com.imageim.yimirror.common.event.EventMessage;
import com.imageim.yimirror.common.network.NetUtil;
import com.imageim.yimirror.common.network.constants.NetConstants;
import com.imageim.yimirror.common.network.listener.NetCallback;
import com.imageim.yimirror.common.network.listener.NetListCallback;
import com.imageim.yimirror.common.network.tool.ParamCreator;
import com.imageim.yimirror.common.ui.GlideUtils;
import com.imageim.yimirror.common.ui.dialog.PromptDialog;
import com.imageim.yimirror.common.ui.tip.TipUtil;
import com.imageim.yimirror.common.util.UserUtil;
import com.imageim.yimirror.ui.adapter.tendency.ThemeItemAdapter;
import com.imageim.yimirror.ui.fragment.DressGuideFragment;
import com.imageim.yimirror.ui.fragment.base.BaseRecyclerViewFragment;
import com.imageim.yimirror.ui.widght.EmptyView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.apache.http.message.BasicNameValuePair;
import org.byteam.superadapter.SuperAdapter;
import org.byteam.superadapter.animation.ScaleInAnimation;
import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Bruce.Zhou on 2018/12/25 18:49.
 * Email: 907160968@qq.com
 */
public class ThemeItemFragment extends BaseRecyclerViewFragment {

    @BindView(R.id.tv_theme)
    TextView tvTheme;
    @BindView(R.id.empty_view)
    EmptyView emptyView;
    @BindView(R.id.tv_theme_desc)
    TextView tvThemeDesc;
    private ThemeItemAdapter adapter;
    private int pageNo = 1;

    FashionRecommendBean.ListBean brandBean;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_theme_item;
    }

    @Override
    protected void initListener() {
        super.initListener();
        emptyView.setOnFinishBtnClickListener(new EmptyView.OnFinishBtnClickListener() {
            @Override
            public void onFinishBtnClick() {
                //                refreshData();
                goback();
            }
        });
        refreshLayout.autoRefresh();
        brandBean = FashionBrandBean.getFashionBrandBean();

        tvTheme.setText(brandBean.getRecommendName());
        tvThemeDesc.setText(brandBean.getRecommendDesc());
        emptyView.setErrorContent("没有图片数据");
        emptyView.setBtnContent("返回");
    }

    @Override
    protected void onRefreshData(RefreshLayout refreshLayout) {
        refreshData();
    }

    @Override
    protected void onLoadMoreData(RefreshLayout refreshLayout) {
        loadMoreData();
    }

    private void refreshData() {
        pageNo = 1;
        List<BasicNameValuePair> params = new ParamCreator()
                .add("currentPage", "" + pageNo)
                .add("photoNo", UserUtil.getPhotoNo())
                .add("recommendType", brandBean.getRecommendType() + "")
                .add("id", brandBean.getId() + "").build();
        NetUtil.getList(getContext(), NetConstants.URL.GET_THEME_ITEMS, params, new NetListCallback<TendencyThemeItemBean>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(List<TendencyThemeItemBean> result) {
                if (result != null && result.size() > 0) {
                    showEmptyView(false);
                    adapter.getData().clear();
                    adapter.getData().addAll(result);
                    adapter.notifyDataSetChanged();
                    recycleView.scrollToPosition(0);
                } else {
                    showEmptyView(true);
                }
                refreshLayout.finishRefresh(200);
            }

            @Override
            public void onFail(int errorCode, String errorMsg) {
                TipUtil.show(errorMsg + errorCode);
                refreshLayout.finishRefresh();
            }
        }, TendencyThemeItemBean.class);
    }

    private void loadMoreData() {
        pageNo++;
        List<BasicNameValuePair> params = new ParamCreator()
                .add("currentPage", "" + pageNo)
                .add("photoNo", UserUtil.getPhotoNo())
                .add("recommendType", brandBean.getRecommendType() + "")
                .add("id", brandBean.getId() + "").build();
        NetUtil.getList(getContext(), NetConstants.URL.GET_THEME_ITEMS, params, new NetListCallback<TendencyThemeItemBean>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(List<TendencyThemeItemBean> result) {
                if (result != null && result.size() > 0) {
                    showEmptyView(false);
                    adapter.getData().addAll(result);
                    adapter.notifyDataSetChanged();
                }
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onFail(int errorCode, String errorMsg) {
                TipUtil.show(errorMsg + errorCode);
                pageNo--;
                refreshLayout.finishLoadMore();
            }
        }, TendencyThemeItemBean.class);
    }

    private void showEmptyView(boolean show) {
        if (show) {
            emptyView.setVisibility(View.VISIBLE);
            recycleView.setVisibility(View.GONE);
        } else {
            emptyView.setVisibility(View.GONE);
            recycleView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public SuperAdapter getAdapter() {
        List<TendencyThemeItemBean> items = new ArrayList<>();
        //        for (int i = 0; i < 50; i++) {
        //            items.add(new TendencyThemeItemBean());
        //        }
        adapter = new ThemeItemAdapter(getContext(), items, R.layout.item_tendency_theme);
        adapter.enableLoadAnimation(480, new ScaleInAnimation());
        return adapter;
    }


    @Override
    public RecyclerViewType getRecycleViewType() {
        return RecyclerViewType.GRID;
    }

    @Override
    public boolean enableRefresh() {
        return true;
    }

    private PromptDialog dialog;

    @Override
    public void onAdapterItemClick(View itemView, int viewType, int position) {
        dialog = new PromptDialog(getContext()).bindView(R.layout.dialog_big_theme_item, new PromptDialog.BindViewListener() {
            @Override
            public void onBindView(View contentView) {
                //                contentView.setOnClickListener(new View.OnClickListener() {
                //                    @Override
                //                    public void onClick(View view) {
                //                        dialog.dismiss();
                //                    }
                //                });
                ImageView ivPhoto = contentView.findViewById(R.id.iv_big_image);
                TendencyThemeItemBean bean = adapter.getData().get(position);
                GlideUtils.display(ivPhoto, bean.getPhotoUrl());

                ImageView ivLike = contentView.findViewById(R.id.iv_big_like);
                if (bean.getLikeFlag() == 1) {
                    ivLike.setSelected(true);
                } else {
                    ivLike.setSelected(false);
                }

                contentView.findViewById(R.id.panel_like).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (bean.getLikeFlag() == 1) {
                            likeOrCancel(position, ivLike, 0);
                        } else {
                            likeOrCancel(position, ivLike, 1);
                        }
                    }
                });
            }
        });
        dialog.setOutsideCanelable(true);
        dialog.show();
        // commit 浏览
        commitViewCount(position);
    }

    /**
     * 上报浏览次数
     */
    private void commitViewCount(int position) {
        TendencyThemeItemBean bean = adapter.getData().get(position);
        List<BasicNameValuePair> params = new ParamCreator()
                .add("contentId", bean.getContentId())
                .add("recommendType", brandBean.getRecommendType() + "")
                .add("photoNo", UserUtil.getPhotoNo()).build();
        NetUtil.postObject(getContext(), NetConstants.URL.COMMIT_VIEW_COUNT, params, new NetCallback<String>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(String result) {
                EventBus.getDefault().post(new EventMessage(EventCode.CODE_REFRESH_VIEW_NUM, brandBean.getId()));
            }

            @Override
            public void onFail(int errorCode, String errorMsg) {
            }
        });
    }

    /**
     * 喜欢与否
     *
     * @param position
     * @param ivLike
     * @param like
     */
    private void likeOrCancel(int position, ImageView ivLike, int like) {
        TendencyThemeItemBean bean = adapter.getData().get(position);
        List<BasicNameValuePair> params = new ParamCreator()
                .add("photoNo", UserUtil.getPhotoNo())
                .add("id", bean.getContentId())
                .add("recommendType", FashionBrandBean.getFashionBrandBean().getRecommendType() + "")
                .add("operateType", "" + like).build();
        NetUtil.postObject(getContext(), NetConstants.URL.SET_LIKE_TO_TENDENCY_PHOTO, params, new NetCallback<String>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(String result) {
                bean.setLikeFlag(like);
                if (like == 1) {
                    ivLike.setSelected(true);
                } else {
                    ivLike.setSelected(false);
                }
                adapter.notifyDataSetChanged();

                EventBus.getDefault().post(new EventMessage(EventCode.CODE_REFRESH_LIKE_NUM, new LikeEventInfo(brandBean.getId(), like)));
            }

            @Override
            public void onFail(int errorCode, String errorMsg) {
                TipUtil.show(errorMsg + errorCode);
            }
        });
    }

    @Override
    public int getSpanCount() {
        return 4;
    }

    @OnClick({R.id.btn_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                goback();
                break;
            default:
                break;
        }
    }

    private void goback() {
        showEmptyView(false);
        adapter.getData().clear();
        adapter.notifyDataSetChanged();
        DressGuideFragment dressGuideFragment = (DressGuideFragment) getParentFragment();
        if (dressGuideFragment != null) {
            //            dressGuideFragment.showFashionTrendFragment();
        }
    }

    public void refresh() {
        brandBean = FashionBrandBean.getFashionBrandBean();
        if (tvTheme != null && tvThemeDesc != null) {
            tvTheme.setText(brandBean.getRecommendName());
            tvThemeDesc.setText(brandBean.getRecommendDesc());
        }
        if (refreshLayout != null) {
            refreshLayout.autoRefresh();
        }
    }

}
